//
//  NearbyListViewController.m
//  HappyTrip
//
//  Created by GeminyXC on 15-3-23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NearbyListViewController.h"
#import "NearbyTableViewCell.h"
#import "NearbyObject.h"
#import "NearbyDetailViewController.h"

#import "UIColor+AddColor.h"


//刷新加载
#import "MJRefresh.h"


@interface NearbyListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *nearbyArr;
@property (nonatomic, retain)NSArray *arr;

@property (nonatomic, retain)NearbyObject *nearbyObjectInfo;

@end

@implementation NearbyListViewController

- (void)dealloc
{
    [_HUD release];
    [_arr release];
    [_nearbyArr release];
    [_tableView release];
    [super dealloc];
}



- (void)handleDataOK
{
    

    for (NSDictionary *dic in self.arr) {
        self.nearbyObjectInfo = [[NearbyObject alloc] initWithNSdictionary:dic];
        if (_nearbyObjectInfo.cover_s.length != 0) {//图片不为空的时候,加入到数组中
        [self.nearbyArr addObject:_nearbyObjectInfo];
        }
//        NSLog(@"%@", nearbyObjectInfo.name);
        [_nearbyObjectInfo release];
    }
    [_tableView reloadData];
    
    NSString *cityStr = [[[self.nearbyArr firstObject] valueForKey:@"city"] objectForKey:@"name"];
    if (cityStr.length != 0) {
    self.title = [NSString stringWithFormat:@"%@(%@)", cityStr, self.title];
    }
    
}

- (void)handleData:(NSInteger)startNumber
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?category=%@&start=%ld&count=20&latitude=%@14&longitude=%@", self.urlID, startNumber, self.lat, self.lng];
    NSLog(@"%@", urlStr);
    
    //没有缓存,想办法在断网的时候可以显示缓存的内容
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [urlStr hash]];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"%d", result);
        
        self.arr = [NSArray array];
        
        //转菊花
        [_HUD removeFromSuperview];
        //        [_HUD hide:YES];//也可以隐藏
        
        self.arr = [responseObject objectForKey:@"items"];
        [self handleDataOK];
        
        //刷新加载
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生未知错误");
        
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        self.arr = [result objectForKey:@"items"];
        
         [_HUD removeFromSuperview];
        [self handleDataOK];

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
        
    }];
//    [_HUD removeFromSuperview];//为什么放这里移除不了???
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = NO;

    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.nearbyArr = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self handleData:0];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;//隐藏分割线
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //注册一个cell
    [self.tableView registerClass:[NearbyTableViewCell class] forCellReuseIdentifier:@"reuse"];
 
    //转菊花
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"正在加载...";
    _HUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_HUD];
    [_HUD release];
    [_HUD show:YES];
    
    //刷新加载
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self.tableView.header endRefreshing];//假刷新
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        static NSInteger i = 1;
        [self handleData:i++ * 20];
    }];

  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.nearbyArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearbyTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    NearbyObject *nearbyObjectInfo = [self.nearbyArr objectAtIndex:indexPath.row];
    cell.nearbyObjectInfo = nearbyObjectInfo;
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;//点击cell不变色
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (VIEW_HEIGHT) * 3 / 7;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选中cell颜色改变后再变回原来的颜色
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NearbyDetailViewController *detailVC = [[NearbyDetailViewController alloc] init];
    NearbyObject *nearbyObjectInfo = [self.nearbyArr objectAtIndex:indexPath.row];
    detailVC.type = nearbyObjectInfo.type;
    detailVC.urlID = nearbyObjectInfo.urlID;
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
